﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.BLL;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class UserController : Controller
    {
        //修改学生信息
        public string UpdateStudent(string stuId, string sex, string bornDate)
        {
            string backTxt = "";
            int age = 0;
            try
            {
                if (string.IsNullOrEmpty(bornDate) == false && string.IsNullOrWhiteSpace(bornDate) == false)
                {
                    //计算年龄
                    TimeSpan timespan = DateTime.Now.Subtract(DateTime.Parse(bornDate));
                    age = (int)timespan.TotalDays / 365;
                }
                int efcount = new UserInfoBLL().UpdateStudent(stuId, sex, bornDate);
                if (efcount == 1)
                {
                    backTxt = "1";
                }
            }
            catch (Exception ex)
            {
                backTxt = "\"error500\"";
                string saveFolder = "Log\\Controller";
                string msg = "User/UpdateStudent，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "({state:" + backTxt + ",age:" + age + "})";
            return back;
        }

        //修改宝宝头像保存数据
        public string UpdateBbHeadImg()
        {
            string backTxt = "";
            try
            {
                string stuId = Request["stuId"];
                string imgPath = Request["imgPath"];
                int count = new UserInfoBLL().UpdateStudentImg(stuId, imgPath);
                backTxt = count + "";
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UpdateBbHeadImg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                backTxt = "\"error500\"";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backTxt + ")";
            return back;
        }

        /// <summary>
        /// 上传宝宝头像
        /// </summary>
        /// <returns></returns>
        public string UploadBbHeadImg()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                if (size > 4194304)
                {
                    return "Max4MB";//图片大小不能超过4MB
                }
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "Upload\\BabyHeadImg";
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名
                //检测文件真实类型
                if (string.IsNullOrEmpty(fileNameHouZui))
                {
                    byte[] fileTmpBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileTmpBytes, 0, file.ContentLength);
                    MemoryStream fileStream = new MemoryStream(fileTmpBytes);
                    string filetype = WebApplication1.Common.FileCommon.GetFileRealType(fileStream);//文件格式名
                    fileStream.Close();
                    fileStream.Dispose();
                    fileNameHouZui = "." + filetype;
                }
                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + "_T" + fileNameHouZui;
                file.SaveAs(fileName);

                string newFilePath = savePath + "\\" + time + fileNameHouZui;
                Common.ImgChuLi.SendSmallImage(fileName, newFilePath, 400, 400, 80, "CUT");//对头像进行裁剪
                //删除上传的原始图片
                System.IO.File.Delete(fileName);
                //组装返回数据
                string fileNameSave = "/Upload/BabyHeadImg/" + time + fileNameHouZui;//保存到数据库的图片路径
                var fileJson = "{\"state\":\"success\",\"filePath\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UploadBbHeadImg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        //上传登录用户头像
        public string UploadUserHeadImg()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                if (size > 4194304)
                {
                    return "Max4MB";//图片大小不能超过4MB
                }
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "Upload\\UserHeadImg";
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名
                //检测文件真实类型
                if (string.IsNullOrEmpty(fileNameHouZui))
                {
                    byte[] fileTmpBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileTmpBytes, 0, file.ContentLength);
                    MemoryStream fileStream = new MemoryStream(fileTmpBytes);
                    string filetype = WebApplication1.Common.FileCommon.GetFileRealType(fileStream);//文件格式名
                    fileStream.Close();
                    fileStream.Dispose();
                    fileNameHouZui = "." + filetype;
                }
                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + "_T" + fileNameHouZui;
                file.SaveAs(fileName);
                string newFilePath = savePath + "\\" + time + fileNameHouZui;
                Common.ImgChuLi.SendSmallImage(fileName, newFilePath, 400, 400, 80, "CUT");//对头像进行裁剪
                //删除上传的原始图片
                System.IO.File.Delete(fileName);
                //组装返回数据
                string fileNameSave = "/Upload/UserHeadImg/" + time + fileNameHouZui;//保存到数据库的图片路径
                var fileJson = "{\"state\":\"success\",\"filePath\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UploadUserHeadImg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        /// <summary>
        /// 上传短视频图片
        /// </summary>
        /// <returns></returns>
        public string UploadVideoImg()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "Upload\\VideoImg_JZ";
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名
                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + "_T" + fileNameHouZui;
                file.SaveAs(fileName);
                string newFilePath = savePath + "\\" + time + fileNameHouZui;
                Common.ImgChuLi.SendSmallImage(fileName, newFilePath, 200, 200, 80, "CUT");//对头像进行裁剪
                //删除上传的原始图片
                System.IO.File.Delete(fileName);
                //组装返回数据
                string fileNameSave = "/Upload/VideoImg_JZ/" + time + fileNameHouZui;//保存到数据库的图片路径
                var fileJson = "{\"state\":\"success\",\"filePath\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UploadVideoImg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        //上传成长档案短视频
        public string UploadGrowVideo()
        {
            try
            {
                HttpFileCollectionBase fileBase = this.HttpContext.Request.Files;
                HttpPostedFileBase file = fileBase.Get(0);
                int size = file.ContentLength;
                string name = file.FileName;
                string type = file.ContentType;
                string serverPath = Server.MapPath("~");

                string saveFolder = "Upload\\Video_JZ";//服务器保存路径
                string savePath = serverPath + saveFolder;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                string fileNameHouZui = Path.GetExtension(name);//文件后缀名

                string time = DateTime.Now.ToString("yyyy-MM-dd_HH_mm_ss_fff");
                string fileName = savePath + "\\" + time + fileNameHouZui;
                file.SaveAs(fileName);

                //组装返回数据
                string fileNameSave = "/Upload/Video_JZ/" + time + fileNameHouZui;//保存到数据库的图片路径
                var fileJson = "{\"state\":\"success\",\"videoURL\":\"" + fileNameSave + "\"}";
                return fileJson;
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UploadGrowVideo，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                return "error500";
            }
        }

        //保存视频数据到数据库
        public string SaveGrowVideo(string userId, string word, string schoolId, string classId, string videoURL, string videoImgURL)
        {
            string backmsg = "";
            try
            {
                int count = new GrowBLL().AddGrowVideo(userId, word, schoolId, classId, videoURL, videoImgURL);
                backmsg = count.ToString();
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/SaveGrowVideo，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                backmsg = "error500";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backmsg + ")";
            return back;
        }

        //保存用户头像数据到数据库
        public string UpdateUserHeadImg()
        {
            string backTxt = "";
            try
            {
                string jzId = Request["jzId"];
                string imgPath = Request["imgPath"];
                int count = new UserInfoBLL().UpdateUserImg(jzId, imgPath);
                backTxt = count + "";
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/UpdateUserHeadImg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                backTxt = "\"error500\"";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backTxt + ")";
            return back;
        }

        //获取用户信息
        public string GetUserInfo()
        {
            string backTxt = "";
            try
            {
                string userId = Request["jzId"];
                JiaZhang model = new UserInfoBLL().GetJiaZhang(userId);
                if (model != null)
                {
                    var data = new
                    {
                        headImgURL = model.headImgURL,
                        guanxi = model.guanxi
                    };
                    backTxt = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/GetUserInfo，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                backTxt = "\"error500\"";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backTxt + ")";
            return back;
        }

        //获取老师发送的消息,定时刷新，将阅读状态改为已读
        public string GetTeacherMsg()
        {
            string backTxt = "";
            try
            {
                string teachId = Request["teachId"];//老师id
                string userId = Request["userId"];//用户id
                string lastTime = Request["lastTime"];//用户id
                string serverAddress = Request["serverAddress"];
                object dt = new UserInfoBLL().GetTeacherMsg(userId, teachId, lastTime, serverAddress);
                backTxt = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
            }
            catch (Exception ex)
            {
                string saveFolder = "Log\\Controller";
                string msg = "User/GetTeacherMsg，" + ex.Message;
                Common.LogManager.AddLog(msg, saveFolder);
                backTxt = "\"error500\"";
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "(" + backTxt + ")";
            return back;
        }

        //记录用户登录日志
        public string AddUserLoginLog(string userId)
        {
            string backTxt = string.Empty;
            int count = 0;
            try
            {
                count = new UserInfoBLL().AddLoginLog(userId);
            }
            catch (Exception ex)
            {
                backTxt = ex.Message;
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "({code:" + count + ",msg:\"" + backTxt + "\"})";
            return back;
        }

        //记录用户登录日志
        public string DelGrowById(string growId)
        {
            string backTxt = string.Empty;
            int count = 0;
            try
            {
                Grow model = null;
                count = new GrowBLL().DelGrowById(growId, out model);
                if (count > 0 && model != null)
                {
                    //删除视频文件
                    string serverPath = Server.MapPath("~");
                    if (string.IsNullOrEmpty(model.videoURL) == false)
                    {
                        string saveFolder = model.videoURL;//服务器保存路径
                        saveFolder = saveFolder.TrimStart('/');
                        string videoFolderPath = saveFolder.Replace("/", "\\");
                        string videoPath = serverPath + videoFolderPath;
                        if (System.IO.File.Exists(videoPath))
                        {
                            //删除视频文件                           
                            System.IO.File.Delete(videoPath);
                        }
                    }
                    if (string.IsNullOrEmpty(model.videoImgURL) == false)
                    {
                        string videoImgFolder = model.videoImgURL;//服务器保存路径
                        videoImgFolder = videoImgFolder.TrimStart('/');
                        string videoImgFolderPath = videoImgFolder.Replace("/", "\\");
                        string imgPath = serverPath + videoImgFolderPath;
                        if (System.IO.File.Exists(imgPath))
                        {
                            //删除视频封面图片
                            System.IO.File.Delete(imgPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                backTxt = ex.Message;
                backTxt = backTxt.Replace("\r\n", " ");
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "({code:" + count + ",msg:\"" + backTxt + "\"})";
            return back;
        }

        //信鸽推送注册错误日志
        public string AddXgRegisterErrorLog(int actionType, string msg)
        {
            string backTxt = string.Empty;
            int count = 0;
            try
            {
                count = new XgBLL().AddXgErrorLog(msg, actionType);
            }
            catch (Exception ex)
            {
                backTxt = ex.Message;
            }
            String callbackFunName = Request["jsoncallback"];
            string back = callbackFunName + "({code:" + count + ",msg:\"" + backTxt + "\"})";
            return back;
        }

    }
}